package com.future.lock.home;


import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.future.baselib.entity.MessageEvent;
import com.future.baselib.utils.DensityUtil;
import com.future.baselib.utils.EventBusUtil;
import com.future.baselib.utils.ToastUtils;
import com.future.baselib.view.CustomViewCenterDialog;
import com.future.lock.R;
import com.future.lock.common.Constants;
import com.future.lock.common.MyApp;
import com.future.lock.common.RefreshDataUtils;
import com.future.lock.common.http.HttpUtils;
import com.future.lock.common.http.response.DefaultHttpResponse;
import com.future.lock.common.http.response.UnreadCountResponse;
import com.future.lock.home.activity.AddMachineActivity;
import com.future.lock.home.activity.LockNotesActivity;
import com.future.lock.home.activity.LockOpeningActivity;
import com.future.lock.home.activity.PeopleManageActivity;
import com.future.lock.home.entity.bean.Lock;
import com.future.lock.home.view.DrawImageView;
import com.future.lock.me.activity.LoginActivity;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 首页Fragment
 */
public class HomeFragment extends Fragment {


    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_no_lock)
    TextView tvNoLock;
    @BindView(R.id.layout_add_machine)
    AutoLinearLayout layoutAddMachine;
    Unbinder unbinder;
    @BindView(R.id.tv_lock_title)
    TextView tvLockTitle;
    @BindView(R.id.layout_open_lock_notes)
    AutoLinearLayout layoutOpenLockNotes;
    @BindView(R.id.layout_people_manage)
    AutoLinearLayout layoutPeopleManage;
    @BindView(R.id.iv_lock_closed)
    ImageView ivLockClosed;
    @BindView(R.id.iv_lock_opening)
    DrawImageView ivLockOpening;
    @BindView(R.id.tv_opening_time)
    TextView tvOpeningTime;
    @BindView(R.id.layout_has_lock)
    View layoutHasLock;
    @BindView(R.id.layout_lock_title)
    View layoutLockTitle;
    @BindView(R.id.iv_lock_title)
    ImageView ivLockTitle;
    private PopupWindow popupWindow;

    int currentPosition = 0;
    private CustomViewCenterDialog payPwdDialog;
    private CustomViewCenterDialog lockPwdDialog;
    private Timer timer;
    private Badge badge;

    public HomeFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBusUtil.register(this);
        initView();
        return view;
    }

    public void initView() {
        if (MyApp.hasLogin()) {
            RefreshDataUtils.refreshLockList(getContext(), refresh -> {
                if (refresh) {
                    if (Constants.lockList != null && Constants.lockList.size() > 0) {//登录有锁
                        layoutLockTitle.setVisibility(View.VISIBLE);
                        tvLockTitle.setText(Constants.lockList.get(0).lock_name);
                        tvNoLock.setVisibility(View.GONE);
                        layoutAddMachine.setVisibility(View.GONE);
                        layoutHasLock.setVisibility(View.VISIBLE);
                        initPopupWindow();
                    } else {//登录无锁
                        layoutLockTitle.setVisibility(View.GONE);
                        tvNoLock.setVisibility(View.VISIBLE);
                        layoutAddMachine.setVisibility(View.VISIBLE);
                        layoutHasLock.setVisibility(View.GONE);
                    }
                }
            });
            hasMessage();
        } else {//未登录
            layoutLockTitle.setVisibility(View.GONE);
            tvNoLock.setVisibility(View.VISIBLE);
            layoutAddMachine.setVisibility(View.VISIBLE);
            layoutHasLock.setVisibility(View.GONE);
        }

        badge = new QBadgeView(getActivity())
                .bindTarget(ivRight)
                .setBadgeGravity(Gravity.END | Gravity.TOP)
                .setGravityOffset(16, 9, true)
                .setBadgeNumber(0);
    }

    private void hasMessage() {
        HttpUtils.getHttpApi().hasUnReadMessage(MyApp.getUserToken()).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                UnreadCountResponse countResponse = new UnreadCountResponse();
                countResponse.parse(response.body());
                if (countResponse.success == 1) {
                    if (countResponse.msg_num != 0) {
                        EventBusUtil.sendEvent(new MessageEvent(Constants.RED_POINT));
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
            }
        });
    }

    private void initPopupWindow() {
        popupWindow = new PopupWindow(getContext());
        ViewGroup rootView = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.layout_lock_list, null);
        for (int i = 0; i < Constants.lockList.size(); i++) {
            final View itemView = getActivity().getLayoutInflater().inflate(R.layout.item_lock_title, null);
            itemView.setTag(i);
            TextView textView = (TextView) itemView.findViewById(R.id.tv_title);
            textView.setText(Constants.lockList.get(i).lock_name);
            if (currentPosition == i) {
                textView.setTextColor(Color.parseColor("#DDB764"));
            }
            if (i == Constants.lockList.size() - 1) {
                itemView.findViewById(R.id.view_line).setVisibility(View.GONE);
            }
            itemView.setOnClickListener(v -> {
                int position = (int) itemView.getTag();
                currentPosition = position;
                tvLockTitle.setText(Constants.lockList.get(position).lock_name);
                popupWindow.dismiss();
            });
            rootView.addView(itemView);
        }
        popupWindow.setContentView(rootView);
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.argb(0, 0, 0, 0)));
        popupWindow.setOnDismissListener(() -> {
            ObjectAnimator animator = ObjectAnimator.ofFloat(ivLockTitle, "rotation", 180f, 0f);
            animator.setDuration(200);
            animator.start();
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBusUtil.unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getCode() == Constants.REFRESH_LOCK_DATA) {
            initView();
        }
        if (event.getCode() == Constants.RED_POINT) {
            badge.setBadgeNumber(-1);
        }
        if (event.getCode() == Constants.RED_POINT_NO) {
            badge.setBadgeNumber(0);
        }
    }

    @OnClick({R.id.iv_left, R.id.iv_right, R.id.layout_add_machine, R.id.iv_lock_closed
            , R.id.layout_open_lock_notes, R.id.layout_people_manage, R.id.layout_lock_title})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_left:
            case R.id.layout_add_machine:
                if (MyApp.hasLogin()) {
                    startActivity(new Intent(getContext(), AddMachineActivity.class));
                } else {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                }
                break;
            case R.id.iv_right:
                if (MyApp.hasLogin()) {
                    startActivity(new Intent(getContext(), LockNotesActivity.class));
                    EventBusUtil.sendEvent(new MessageEvent(Constants.RED_POINT_NO));
                } else {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                }
                break;
            case R.id.layout_open_lock_notes://开锁记录
                String lock_id = Constants.lockList.get(currentPosition).lock_id;
                Intent intent = new Intent(getContext(), LockNotesActivity.class);
                intent.putExtra("lock_id", lock_id);
                startActivity(intent);
                EventBusUtil.sendEvent(new MessageEvent(Constants.RED_POINT_NO));
                break;
            case R.id.layout_people_manage://成员管理
                String lock_id1 = Constants.lockList.get(currentPosition).lock_id;
                String lock_name = Constants.lockList.get(currentPosition).lock_name;
                Intent intent1 = new Intent(getContext(), PeopleManageActivity.class);
                intent1.putExtra("lock_id", lock_id1);
                intent1.putExtra("lock_name", lock_name);
                startActivity(intent1);
                break;
            case R.id.iv_lock_closed:
                inputPwdDialog();
                break;
            case R.id.layout_lock_title:
                ViewGroup viewGroup = (ViewGroup) popupWindow.getContentView();
                for (int i = 0; i < viewGroup.getChildCount(); i++) {
                    ((TextView) viewGroup.getChildAt(i).findViewById(R.id.tv_title)).setTextColor(Color.WHITE);
                    if (i == currentPosition) {
                        ((TextView) viewGroup.getChildAt(i).findViewById(R.id.tv_title)).setTextColor(Color.parseColor("#DDB764"));
                    }
                }
                popupWindow.showAsDropDown(tvLockTitle, -DensityUtil.dip2px(getContext(), 40f), 0);
                ObjectAnimator animator = ObjectAnimator.ofFloat(ivLockTitle, "rotation", 0f, 180f);
                animator.setDuration(200);
                animator.start();
                break;
        }
    }

    private void inputPwdDialog() {
        View rootView = getActivity().getLayoutInflater().inflate(R.layout.dialog_pay_password, null);
        EditText pet = (EditText) rootView.findViewById(R.id.et_pwd);
        pet.post(() -> showSoftKeyboard(pet));
        rootView.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lockPwdDialog.dismiss();
            }
        });
        rootView.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lockPwdDialog.dismiss();
                String pwd = pet.getText().toString().trim();
                if (pwd.length()<6) {
                    Toast.makeText(getContext(), "密码应该介于6-12位之间", Toast.LENGTH_SHORT).show();
                    return;
                }
                openLock(pwd);
            }
        });
        lockPwdDialog = new CustomViewCenterDialog(getContext())
                .setView(rootView)
                .builder()
                .show();
        pet.requestFocus();
    }

    private void openLock(String password) {
        Lock lock = Constants.lockList.get(currentPosition);
        HttpUtils.getHttpApi()
                .openLock(MyApp.getUserToken(), lock.lock_id, password)
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        DefaultHttpResponse httpResponse = new DefaultHttpResponse();
                        httpResponse.parse(response.body());
                        if (httpResponse.success != 1) {
                            openLockFail(httpResponse.msg);
                            if (httpResponse.code == 112) {
                                RefreshDataUtils.logout(getContext());
                            }
                        } else {
                            ivLockClosed.setVisibility(View.GONE);
                            ivLockOpening.setVisibility(View.VISIBLE);
                            tvOpeningTime.setVisibility(View.VISIBLE);
                            tvOpeningTime.setText("开锁中...(29s)");
                            handler.sendEmptyMessageDelayed(1, 1000);
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        String message = t.getMessage();
                        if ("timeout".equals(message)) {
                            message = "开锁超时，请重启app";
                        }
                        openLockFail(message);
                    }
                });
    }

    private int lunxunCount = 29;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                lunxunCount--;
                tvOpeningTime.setText("开锁中...("+lunxunCount+"s)");
                if (lunxunCount<=25) {
                    lunxunLock();
                }else{
                    handler.sendEmptyMessageDelayed(1,1000);
                }
            }
        }
    };

    private void lunxunLock() {
        HttpUtils.getHttpApi()
                .lunxunLock(MyApp.getUserToken(), Constants.lockList.get(currentPosition).lock_id)
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        DefaultHttpResponse defaultHttpResponse = new DefaultHttpResponse();
                        defaultHttpResponse.parse(response.body());
                        if (defaultHttpResponse.success == 1) {
                            lunxunCount = 29;
                            openLockSuc();
                        } else {
                            if (lunxunCount <= 0) {
                                openLockFail("开锁失败");
                            } else {
                                handler.sendEmptyMessageDelayed(1, 1000);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        openLockFail("开锁失败");
                    }
                });
//        openLockSuc();
    }

    public void openLockSuc() {
        lunxunCount = 29;
        Intent intent = new Intent(getContext(), LockOpeningActivity.class);
        intent.putExtra("position", currentPosition);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.open_lock_in, R.anim.open_lock_out);
        ivLockClosed.setVisibility(View.VISIBLE);
        ivLockOpening.setVisibility(View.GONE);
        tvOpeningTime.setVisibility(View.GONE);
    }

    public void openLockFail(String msg) {
        lunxunCount = 29;
        handler.removeMessages(1);
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
        ivLockClosed.setVisibility(View.VISIBLE);
        ivLockOpening.setVisibility(View.GONE);
        tvOpeningTime.setVisibility(View.GONE);
    }

    public void showSoftKeyboard(EditText et) {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(et, 0);
    }


}
